import * as db from "./db";
import utils from "./utils";
import axios from "axios";
import askDeepseek from "./askDeepseek";

let users = Bun.file("users.txt");
if (users) {
  users = await users.text();
  users = users
    .split("\n")
    .filter((a) => a)
    .map((a) => {
      return a.replace(/\n/g, "").replace(/\r/g, "");
    });
}
console.log(users);

interface Command {
  pattern: string;
  handler: (
    coin: string,
    wxid: string,
    botid: string,
    content: string,
    sender: string,
  ) => Promise<void>;
}

// let askCaidan2 = async (content: string, wxid: string, botid: string) => {
//       await utils.sendMessage(wxid, '智能分析中');
//       let { data } = await axios.post("https://caidan2.com/ai/bot", {
//         botid: botid,
//         userid: wxid,
//         question: content,
//       });
//       console.log(data)
//       await utils.sendMessage(wxid, data.content);
//     }

let askDeep = async (content: string, wxid: string, botid: string) => {
  let ret = await askDeepseek(wxid, content);
  await utils.sendMessage(wxid, ret.trim());
};
const commands: Command[] = [
  // {
  //   pattern: "?",
  //   handler: askDeep,
  // },
  // {
  //   pattern: "0x",
  //   handler: async (ca, wxid,botid, content)=>{
  //     utils.sendMessage(wxid, 'https://rgswap.vip?ca='+content)
  //   }
  // },
  // {
  //   pattern: "？",
  //   handler: askDeep,
  // },
  {
    pattern: "币价关注",
    handler: async (coin: string, wxid: string) => {
      await db.toggleCoinChat(coin, wxid, true);
      await utils.sendMessage(wxid, "关注成功 " + coin);
    },
  },
  // {
  //   pattern: "0x",
  //   handler: async (ca: string, wxid: string) => {
  //     console.log(ca);
  //     if (ca.length == 40) {
  //       let res = await fetch("https://chat.rgbot.vip/token/0x" + ca);
  //       let text = await res.text();
  //       if (text && text.indexOf("名称") >= 0) utils.sendMessage(wxid, text);
  //     }
  //   },
  // },
  {
    pattern: "$",
    handler: async (cmd, wxid, botid, raw, sender) => {
      let res = await fetch("https://chat.rgbot.vip/chat", {
        method: "POST",
        body: JSON.stringify({
          uid: sender,
          content: "$" + cmd,
          platform: "wechat",
        }),
      });
      let text = await res.text();
      if (text) {
        utils.sendMessage(wxid, text);
      }
    },
  },
  {
    pattern: "/",
    handler: async (cmd, wxid, botid, raw, sender) => {
      let res = await fetch("https://chat.rgbot.vip/chat", {
        method: "POST",
        body: JSON.stringify({
          uid: sender,
          content: "$" + cmd,
          platform: "wechat",
        }),
      });
      let text = await res.text();
      if (text) {
        utils.sendMessage(wxid, text);
      }
    },
  },
  {
    pattern: "币价取关",
    handler: async (coin: string, wxid: string) => {
      await db.toggleCoinChat(coin, wxid, false);
      await utils.sendMessage(wxid, "取关成功 " + coin);
    },
  },
  {
    pattern: "查看设置",
    handler: async (_: string, wxid: string) => {
      const coins = await db.getMyCoins(wxid);
      await utils.sendMessage(
        wxid,
        `
机器人设置
币安推送 ${db.getSettings(wxid, "binance_status") ? "开" : "关"}
热狗推送 ${db.getSettings(wxid, "regou_status") ? "开" : "关"}
币价关注列表  ${coins.join(",")}`,
      );
    },
  },
  {
    pattern: "热狗推送",
    handler: async (status: string, wxid: string) => {
      if (!status.trim()) {
        let regouStatus = await db.getSettings(wxid, "regou_status");
        await utils.sendMessage(
          wxid,
          "热狗推送 " + (regouStatus ? "开" : "关"),
        );
        return;
      }
      const newStatus = await db.toggleRegouStatus(wxid, status);
      await utils.sendMessage(wxid, "热狗推送 " + newStatus);
    },
  },
  {
    pattern: "id",
    handler: async (status: string, wxid: string) => {
      await utils.sendMessage(wxid, wxid);
    },
  },
  {
    pattern: "群发用户消息:",
    handler: async (content, wxid, botid, raw, sender) => {
      console.log(wxid);
      console.log(botid);
      if (sender) {
        return;
      }
      await utils.sendMessage("filehelper", content);
      await utils.sendMessage(
        "filehelper",
        "群发用户数:" + users.length + "\n群发内容:" + content,
      );

      for (let i in users) {
        await utils.sendMessage(users[i], content);
        console.log(`群发用户消息: ${i}/${users.length}`, `(${users[i]})`);
        await Bun.sleep(Math.round(Math.random() * 3 * 1000));
      }
    },
  },
  {
    pattern: "开启打满推送",
    handler: async (status, wxid, botid, raw, sender) => {
      if (sender) {
        return;
      }
      let res = await fetch(
        "https://four-api.minapp.xin/api/four/rooms/" + botid,
        {
          method: "POST",
          body: JSON.stringify({
            roomid: wxid,
            enable: true,
          }),
        },
      );
      let { message } = await res.json();
      await utils.sendMessage(wxid, message);
    },
  },

  {
    pattern: "关闭打满推送",
    handler: async (status, wxid, botid, raw, sender) => {
      if (sender) {
        return;
      }
      let res = await fetch(
        "https://four-api.minapp.xin/api/four/rooms/" + botid,
        {
          method: "POST",
          body: JSON.stringify({
            roomid: wxid,
            enable: false,
          }),
        },
      );
      let { message } = await res.json();
      await utils.sendMessage(wxid, message);
    },
  }

  // {
  //   pattern: "开启打满推送",
  //   handler: async (status, wxid, botid, raw, sender) => {
  //     if (sender) {
  //       return;
  //     }
  //     let res = await fetch(
  //       "https://four-api.minapp.xin/api/four/rooms/" + botid,
  //       {
  //         method: "POST",
  //         body: JSON.stringify({
  //           roomid: wxid,
  //           enable: true,
  //         }),
  //       },
  //     );
  //     let { message } = await res.json();
  //     await utils.sendMessage(wxid, message);
  //   },
  // },
  {
    pattern: "监听推特",
    handler: async (status, wxid, botid, raw, sender) => {
      if (sender) {
        return;
      }
      let res = await fetch("https://chat.rgbot.vip/hook/subscribe", {
        method: "POST",
        body: JSON.stringify({
          wxid: wxid,
          userName: status,
        }),
      });
      let { message } = await res.json();
      await utils.sendMessage(wxid, message);
    },
  },
  {
    pattern: "push",
    handler: async (status, wxid, botid) => {
      await utils.sendMessage(
        wxid,
        `https://caidan2.com/api/webot/push/${botid}/${wxid}?content=hello`,
      );
    },
  },
  {
    pattern: "币安推送",
    handler: async (status: string, wxid: string) => {
      if (!status.trim()) {
        let binanceStatus = db.getSettings(wxid, "binance_status");
        await utils.sendMessage(
          wxid,
          "币安推送 " + binanceStatus ? "开" : "关",
        );
      }
      const newStatus = await db.toggleBinanceStatus(wxid, status);
      await utils.sendMessage(wxid, "币安推送 " + newStatus);
    },
  },
  {
    pattern: "通知绑定",
    handler: async (shopid: string, wxid: string, botid: string) => {
      console.log("通知绑定", shopid, wxid, botid);
      let bot = await utils.getMyself();
      let user = await utils.getContact(wxid);
      let { data } = await axios.post("https://caidan2.com/api/webot/bind", {
        shopid,
        userid: wxid,
        botid,
        bot: bot,
        user: user,
      });
      console.log(data);
      await utils.sendMessage(wxid, data.content);
    },
  },
];

export default async function (
  content: string,
  wxid: string,
  botid: string,
  sender: string,
) {
  for (const command of commands) {
    content = content.trim();
    if (content.startsWith(command.pattern)) {
      const coin = content.replace(command.pattern, "").trim();
      try {
        await command.handler(coin, wxid, botid, content, sender);
      } catch (err) {
        console.error(err);
      }
      break;
    }
  }

  try {
    if (content) {
      const matches = content.match(
        /(0x[a-fA-F0-9]{40}|[1-9A-HJ-NP-Za-km-z]{32,44})/g,
      );
      if (matches?.length > 0) {
        let ca = matches[0];
        let text = await (
          await fetch(
            `https://chat.rgbot.vip/token/${ca}?platform=wechat&room=${wxid}&uid=${sender}`,
          )
        ).text();
        if (text && text.includes("名称")) {
          utils.sendMessage(wxid, text);
        }
      }
    }
  } catch (err) {
    console.error(err);
  }
}
